﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WISD.Common
{
    /// <summary>
    /// 类    名：NullHandle
    /// 描    述：Null处理类
    /// 创建时间：2010/12/22
    /// </summary>
    public class NullHelper
    {
        /// <summary>
        /// 判断是否是Null，如果是Null，返回True
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool IsNull(object obj)
        {
            if (object.Equals(obj, null) || object.Equals(obj, DBNull.Value))
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 判断一对象是否是Null，如果是Null，返回预设值，如果不是Null，原值返回
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="strType"></param>
        /// <param name="objReturnValue"></param>
        /// <returns></returns>
        public static object NullReturn(object obj, object objReturnValue)
        {
            if (IsNull(obj))
            {
                //如果是Null，返回预设值
                return objReturnValue;
            }
            else
            {
                //如果不是Null，原值返回
                return obj;
            }
        }


        /// <summary>
        /// 引入泛型处理Null，减少装箱、拆箱带来的损耗
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public static T NullProcess<T>(object obj, T t)
        {
            try
            {
                if (IsNull(obj))
                {
                    return t;
                }
                else
                {
                    if (typeof(T) == typeof(string))
                    {
                        return (T)obj;
                    }
                    else if (typeof(T) == typeof(int))
                    {
                        return (T)(object)int.Parse(obj.ToString());
                    }
                    else if (typeof(T) == typeof(DateTime))
                    {
                        return (T)(object)DateTime.Parse(obj.ToString());
                    }
                    else
                    {
                        throw new NotImplementedException();
                    }
                }
            }
            catch (Exception)
            {
                return t;
            }
        }

    }
}
